package com.xoa.controller.workflow;


import com.xoa.model.workflow.FlowManageLog;
import com.xoa.service.workflow.FlowManageLog.FlowManageLogService;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.http.Response;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import javafx.scene.chart.ValueAxis;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/LogController")
public class FlowManagerLogController {

    @Autowired
    private FlowManageLogService flowManagerLogService;

    /**
     *
     * @param pageSize
     * @param page
     * @param useFlag
     * @return
     */
    @RequestMapping(value = "/selectAllLogByPage")
    @ResponseBody
    public ToJson selectAllLogByPage(
            @RequestParam(value = "pageSize")Integer pageSize,
                                     @RequestParam(value = "page")Integer page,
                                     @RequestParam(value = "useFlag")boolean useFlag
    ){
        Map map = new HashMap();
        ToJson toJson = new ToJson();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        map.put("pageParams",pageParams);
        List<FlowManageLog> list = flowManagerLogService.selectAllLogByPage(map);
        if (list.size()>0){
            toJson.setObj(list);
            toJson.setFlag(0);
            toJson.setMsg("ok");
        }
        return toJson;
    }

    /**
     *
     * @param pageSize
     * @param page
     * @param useFlag
     * @param flowName
     * @param type
     * @return
     */
    @RequestMapping("/selectAllLogByPageAndTJ")
    @ResponseBody
    public ToJson selectAllByPage(@RequestParam(value = "pageSize",required = false)Integer pageSize,
                                  @RequestParam(value = "page",required = false)Integer page,
                                  @RequestParam(value = "useFlag",required = false)Boolean useFlag,
                                  @RequestParam(value = "flowName",required = false)String flowName,
                                  @RequestParam(value = "type",required = false)Integer type,
                                  @RequestParam(value = "startTime",required = false)String startTime,
                                  @RequestParam(value = "endTime",required = false)String endTime,
                                  @RequestParam(value = "userId",required = false)String userId,
                                  @RequestParam(value = "ip",required = false)String ip){

        ToJson<Object> toJson=new ToJson();
        Map map = new HashMap();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        map.put("pageParams",pageParams);

        if(!StringUtils.checkNull(flowName)){
            map.put("flowName",flowName);
        }

        if(type!=null&&type!=0){
            map.put("type",type);
        }

        if(!StringUtils.checkNull(startTime)){
            map.put("startTime",startTime);
        }
        if(!StringUtils.checkNull(endTime)){
            map.put("endTime",endTime);
        }


        if(!StringUtils.checkNull(ip)){
            map.put("ip",ip);
        }
        if(!StringUtils.checkNull(userId)){
            String newUserId = userId.substring(0,userId.length()-1);
            map.put("userId",newUserId);
        }
        List list = flowManagerLogService.selectAllLogByPageAndTJ(map);
        if(list !=null && list.size()>0){
            toJson.setObj(list);
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setTotleNum(pageParams.getTotal());
        }
        return toJson;
    }

    /**
     *
     * @param id  被删除信息的id（唯一标识）
     * @return
     */
    @RequestMapping("/deleteLog")
    @ResponseBody
    public ToJson deleteLog(@RequestParam(value = "id")Integer id){
        ToJson toJson = new ToJson();
        try {
            if(flowManagerLogService.deleteLog(id)){

                toJson.setFlag(0);
                toJson.setMsg("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return toJson;
    }

    /**
     *
     * @param flow_id 流程号(唯一)
     * @param flow_name 流程名称
     * @param time 发生时间
     * @param ip IP地址
     * @param content 内容
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     * @throws Exception
     */
    @RequestMapping("/LogExcelOut")
    @ResponseBody
    public ToJson<FlowManageLog> LogExcelOut(@RequestParam(value = "flow_id")String flow_id,
                                             @RequestParam(value = "flow_name")String flow_name,
                                             @RequestParam(value = "time")String time,
                                             @RequestParam(value = "ip") String ip,
                                             @RequestParam(value = "content")String content,
                                             HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        String sqlType = "xoa" + (String) httpServletRequest.getSession().getAttribute("loginDateSouse");
        ContextHolder.setConsumerType(sqlType);

        ToJson<FlowManageLog> toJson = new ToJson<FlowManageLog>();

        List<FlowManageLog> list = flowManagerLogService.getAllLog();
        HSSFWorkbook hssfWorkbook = ExcelUtil.makeExcelHead("用户信息导出",6);
        String[] secondTitles = {"流程号","流程名称","操作人","发生时间","IP地址","内容"};
        HSSFWorkbook hssfWorkbook1 = ExcelUtil.makeSecondHead(hssfWorkbook,secondTitles);
        String[] beanProperty = {"flow_id","flow_name","CZR","time","ip","content"};
        HSSFWorkbook hssfWorkbook2 = null;
        try {
            hssfWorkbook2 = ExcelUtil.exportExcelData(hssfWorkbook1,list,beanProperty);
            OutputStream outputStream = httpServletResponse.getOutputStream();

            String filename = "用户信息导出.xls";
            filename = FileUtils.encodeDownloadFilename(filename,httpServletRequest.getHeader("user-agent"));
            httpServletResponse.setContentType("application/vnd.ms-excel");
            httpServletResponse.setHeader("content-disposition","attachment;filename=" + filename);
            hssfWorkbook2.write(outputStream);
            outputStream.close();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return toJson;
    }

    @RequestMapping(value = "/logMain")
    public String logMain(){
        return "/app/workflow/work/managementLog";
    }

}
